package com.xgc.erp.info.customer.ctrl;

import com.jfinal.aop.Inject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.xgc.common.base.BaseController;
import com.xgc.common.config.Constan;
import com.xgc.common.model.Customer;
import com.xgc.common.vo.Feedback;
import com.xgc.erp.info.customer.service.CustomerService;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;

//@ControllerBind(path="/erp/info/customer")
public class CustomerController extends BaseController {
    @Inject
    private CustomerService service;

    public void index() {
        render("index.html");
    }

    public void list(){
        String customerName = get("customerName");
        Record record = new Record();
        record.set("customer_name",customerName);
        String creator = getVisitor().getCode();
        record.set("creator=",creator);

        // 管理员和老板，查看全部客户
        String sql = "select * from sys_user_role where role_code in ('boss','admin')";
        List<Record> roleList = Db.find(sql);
        for(Record r:roleList){
            if(creator.equals(r.getStr("user_code"))){
                record.remove("creator=");
                break;
            }
        }
        renderJson(service.queryForList(getParaToInt("pageNumber",1), getParaToInt("pageSize",10),record,"order by create_time desc"));
    }

    public void add() {
        render("add.html");
    }

    public void save() {
        Customer customer=getBean(Customer.class);
        Integer customerId = service.getPrimaryKey(Constan.SEQ_CUSTOMER);
        customer.setCustomerId(customerId);
        customer.setCreator(getVisitor().getCode());
        customer.setUpdateTime(new Date());
        boolean flag = service.isExit(service.getPK(),customerId.toString());
        if(flag){
            setException("主键已存在");
        }else {
            flag = service.save(customer);
            if(!flag) {
                setException("保存失败");
            }
        }
        render("add.html");
    }

    public void edit() throws UnsupportedEncodingException {
        Customer customer =(Customer) service.findById(URLDecoder.decode(getPara("primaryKey"),"utf-8"));
        Customer parent = (Customer) service.findById(customer.getCustomerId().toString());
        setAttr("customer", customer);
        render("edit.html");
    }

    public void update() {
        Customer customer=getBean(Customer.class);
        customer.setModifier(getVisitor().getCode());
        customer.setUpdateTime(new Date());
        service.update(customer);
        setAttr("customer", customer);
        render("edit.html");
    }

    public void delete() {
        service.deleteByIds(getIds());
        renderJson(Feedback.success());
    }

}
